package honest.playmusic.ui;

import honest.playmusic.bean.Music;
import honest.playmusic.data.ConfigData;
import honest.playmusic.exception.FileCorruptException;
import honest.playmusic.impl.UiImpl;
import honest.playmusic.sqlite.MusicDb;
import honest.playmusic.util.FormatString;
import honest.playmusic.util.MusicPlayerManager;
import honest.playmusic.util.OnlineLrcManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.naming.ConfigurationException;
/**
 * 音乐播放器的控制页面
 * 设计模式状态模式的经典体现
 * @author 李跃东
 * @mail androiddevelop@qq.com
 * @date 2013-11-8
 */
public class CommandUi implements UiImpl {
	private boolean isExit=false;
	private List<Music> playList=new ArrayList<Music>(); //播放列表
	private int index=0; //播放歌曲位置
	private static MusicPlayerManager musicPlayerMusic=null;

	final boolean ON=true;
	final boolean OFF=false;
	private boolean lrcState=ON; //歌词初始状态打开


	private  Scanner in=new Scanner(System.in);

	private SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");

	@Override
	public void start() {
		System.out.println("欢迎使用!!");
		showPrompt();

		//自动切歌线程
		new Thread(){
			public void run(){
				while(!isExit){
					if(musicPlayerMusic!=null){
						if(musicPlayerMusic.isComplete()){
							nextMusicState();
						}
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		String cmd="s";
		while(!isExit){

			switch(cmd){

			//搜索
			//搜索阶段停止播放歌曲
			case "s": searchState(); break;

			//下一曲
			case "n": nextMusicState(); break;

			//歌词显示切换
			case "l": lrcSwitchState(); break;

			//更换歌词
			case "c": changeLrcState(); break;

			//更新歌曲库
			//更新阶段停止播放歌曲
			case "u": updateState(); break;

			//退出
			case "q": exitState(); break;

			//输入错误或者指定播放歌曲
			default:  defaultState(cmd); 
			}

			if(!isExit)
				cmd=in.nextLine().trim().toLowerCase();
		}
		in.close();
	}


	/**
	 * 状态切换
	 * @param cmd
	 */
	private boolean stateSwitch(String cmd){
		switch(cmd){
		case "s": searchState(); break;
		case "n": nextMusicState(); break;
		case "l": lrcSwitchState(); break;
		case "c": changeLrcState(); break;
		case "u": updateState(); break;
		case "q": exitState(); break;
		default : return false;
		}
		return true;
	}


	/**
	 * 显示提示
	 */
	private void showPrompt(){
		System.out.println("操作详单:\ns----搜索\nn----下一曲\nu----更新歌曲库\nl----显示歌词\nc----更换歌词\nq----退出\n");
	}


	/**
	 * 格式化搜索结果
	 */
	private void showSearchMusic(){
		Music music;
		int i;
		for(int j=0;j<ConfigData.SHOW_WIDTH;j++)
			System.out.print("*");
		System.out.println("");
		String tmp;
		for(i=0;i<playList.size();i++){
			music=playList.get(i);
			tmp=FormatString.getFormatString(getFormatOrder(i+1)+" "+music.getMusicName()
					+"("+music.getMusicAuthor()+")"
					+" <"+sdf.format(music.getMusicTime())+">",60,false);
			System.out.printf(tmp);
			if(i%2==1)
				System.out.println();
		}
		if(i%2==1)
			System.out.println();
		for(int j=0;j<ConfigData.SHOW_WIDTH;j++)
			System.out.print("*");
		System.out.println("");
	}

	/**
	 * 格式化序号
	 * @param str 要格式化的序号
	 * @return 格式化后的序号
	 */
	private String getFormatOrder(int num){
		int len=(playList.size()+"").length();
		int tmp=1;
		String res;
		for(int i=1;i<=len;i++){
			tmp=tmp*10;
			if(num<tmp){
				res=num+"";
				for(int j=0;j<len-i;j++)
					res="0"+res;
				return res;
			}
		}
		return "";
	}



	/**
	 * 下一首歌状态
	 */
	private void nextMusicState(){
		if(playList.isEmpty()){
			System.out.println("播放列表为空");
			//转换状态
			searchState();
		}else{
			if(musicPlayerMusic!=null){
				musicPlayerMusic.stopMusic();
				musicPlayerMusic=null;
			}
			Music music=playList.get((++index)%playList.size());
			musicPlayerMusic=new MusicPlayerManager(music);
			System.out.println("\n下一首:");
			printMusicInfo(music);
			musicPlayerMusic.playMusic();
		}
	}

	/**
	 * 搜索状态
	 */
	private void searchState(){
		if(musicPlayerMusic!=null){
			musicPlayerMusic.stopMusic();
			musicPlayerMusic=null;
		}
		System.out.println("输入要检索的歌曲名或歌手");
		String cmd=in.nextLine().trim().toLowerCase();
		//状态切换成功，不在继续该状态下后续操作
		if(stateSwitch(cmd)) 
			return ;
		playList.clear();
		playList=new MusicDb(ConfigData.MUSIC_DIRECTORY_PATH).query(cmd);
		if(playList.size()==0){
			System.out.println("检索内容不存在！！！\n");
			searchState();
		}else{
			showSearchMusic();
			chooseMusicState();
		}
	}


	/**
	 * 选择播放音乐状态
	 */
	private void chooseMusicState(){
		System.out.println("输入要播放的歌曲");  
		String cmd=in.nextLine().trim().toLowerCase();
		//状态切换成功，不在继续该状态下后续操作
		if(stateSwitch(cmd)) 
			return ;
		try{
			index=Integer.valueOf(cmd);
			musicPlayerMusic=new MusicPlayerManager(playList.get(--index%playList.size()));
			printMusicInfo(playList.get(index));
			musicPlayerMusic.playMusic();
		}catch(NumberFormatException e){
			System.out.println("输入有误，请重新输入!!");
			chooseMusicState();
		}
	}

	/**
	 * 更新状态
	 */
	private void updateState(){
		if(musicPlayerMusic!=null){
			musicPlayerMusic.stopMusic();
			musicPlayerMusic=null;
		}
		MusicDb db=new MusicDb(ConfigData.MUSIC_DIRECTORY_PATH);
		try {
			db.update();
		} catch (ConfigurationException e) {
			e.printStackTrace();
		} catch (FileCorruptException e) {
			e.printStackTrace();
		}

		searchState();
	}


	/**
	 * 退出状态
	 */
	private void exitState(){
		if(musicPlayerMusic!=null){
			musicPlayerMusic.stopMusic();
		}
		isExit=true;
		System.out.println("\n谢谢你的使用!!");
	}

	/**
	 * 输入默认状态处理
	 * @param cmd
	 */
	private void defaultState(String cmd){
		int input=-1;
		try{
			input=Integer.valueOf(cmd);
		}catch(NumberFormatException e){
			//输入错误
		}
		if(input==-1){
			System.out.println("输入错误，请重新输入");
		}else{
			if(musicPlayerMusic!=null){
				musicPlayerMusic.stopMusic();
				Music music=playList.get((input-1)%playList.size());
				printMusicInfo(music);
				musicPlayerMusic=new MusicPlayerManager(music);
				musicPlayerMusic.playMusic();
			}
		}
	}

	/**
	 * 格式化输出音乐信息
	 * @param music 准备播放的音乐
	 */
	private void printMusicInfo(Music music){
		for(int i=0;i<ConfigData.SHOW_WIDTH;i++)
			System.out.print("*");
		System.out.println("");
		System.out.println(music.getMusicName());
		String author=music.getMusicAuthor();
		System.out.println("歌手: "+author+"    收录歌曲: "+
				new MusicDb(ConfigData.MUSIC_DIRECTORY_PATH).queryAuthor(author)
				+"首    时长: "+sdf.format(music.getMusicTime()).replace(':', '分')+"秒");
		for(int i=0;i<ConfigData.SHOW_WIDTH;i++)
			System.out.print("*");
		System.out.println("");
	}

	/**
	 * 更换歌词状态
	 */
	private void changeLrcState(){
		if(lrcState){
			if(musicPlayerMusic!=null){
				OnlineLrcManager onlineLrcManager=new OnlineLrcManager();
				onlineLrcManager.getLrcAndWriteFile(playList.get(index));
				musicPlayerMusic.resetLrc();
			}else{
				System.out.println("你还没开始播放歌曲呢");	
			}
		}else{
			System.out.println("歌词没有显示，指令无效");
			searchState();
		}
	}

	/**
	 * 歌词显示切换状态
	 * 保持原有状态
	 */
	private void lrcSwitchState(){
		onOff();
		if(lrcState){
			musicPlayerMusic.showLrc();
		}else{
			musicPlayerMusic.unShowLrc();
		}
	}




	/**
	 * 始终显示歌词开关切换
	 */
	private void onOff(){
		if(lrcState){
			lrcState=OFF;
			System.out.println("歌词显示开关当前状态---------->关闭");
		}else{
			lrcState=ON;
			System.out.println("歌词显示开关当前状态---------->打开");
		}
		searchState();
	}

}
